from rest_framework import serializers
from .models import Region

# 新增/编辑验证基类
class AddEditValidateBase(serializers.ModelSerializer):
    parentCode = serializers.CharField(required=False)
    remark = serializers.CharField(required=False)
    
    def validate_parentCode(self, val):
        if val:
            region = Region.objects.only('code').filter(code=val)
            if not region.exists():
                raise serializers.ValidationError("父级对象不存在")
            return region.first()
        return None
    
# 新增
class AddValidate(AddEditValidateBase):
    
    class Meta:
        model = Region
        exclude = '__all__'

# 编辑
class EditValidate(AddEditValidateBase):
    def validate_code(self, val):
        if not Region.objects.filter(code=val).exists():
            raise serializers.ValidationError("编辑对象不存在")
        return val
    
    class Meta:
        model = Region
        fields = '__all__'
